# Create your views here.
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.template import Context,loader
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required

from game.combat.models import combat, combatant, combatMessage
from game.actions.models import action
from game.combat.combatActionRequest import combatActionRequest
from game.encounter.models import encounter, combatEncounter, engagedPlayer
from game.monster.views import getIndThumb
from game.profile.models import profile
from game.common.logger import logger

combatURLPath = r'combat/'

#@login_required
def showCombat(request):
    logger.debug("Viewing Combat started")
    response = HttpResponse()
    #get the user and find what combat they're a part of
    try:
        prof = profile.objects.get(id = request.session['profileID'])
        cmb = engagedPlayer.objects.get(profile = prof).combat
    except ObjectDoesNotExist:
        #player not engaged in combat
        logger.error("showCombat called for user not in combat: %s"%(profile.user))
        response.write("You aren't in combat")
        return response
    
    logger.debug("Combat ID: %s"%(cmb.id))
    if request.method == "POST":
    #See what the user posted
        if request.POST.has_key('action'):
        #User posted an action
            act = request.POST['action']
            target = request.POST['target']
            act = action.objects.get(id=act)
            target = combatant.objects.get(id=target)
            car = combatActionRequest(act, cmb.currentCombatant, target, cmb)
            cmb.processRequest(car)
        elif request.POST.has_key('endCombat') and cmb.currentState == 3:
        #User is ending combat and combat is actually over
            cmb.tearDown()
            response.write("combat is over")
            return response
    logger.debug("Building combat view context")
    c = Context()
    c['path'] = request.get_full_path()
    c['sideACombatants'] = cmb.sideA.allMonsters()
    c['sideBCombatants'] = cmb.sideB.allMonsters()
    c['Messages'] = getMessages(cmb)
    c['actionsAvailable'] = cmb.currentCombatant.individual.getAllActions()
    c['currentEnemies'] = cmb.currentCombatant.getEnemies()
    c['currentCombatant'] = cmb.currentCombatant
    c['currentState'] = cmb.currentState
    c['isActive'] = cmb.isActive
    logger.debug("Rendering combat")
    response.write(loader.render_to_string('combat/combat.html', c))
    return response
    
def getMessages(cmb):
    messages = combatMessage.objects.filter(combat=cmb)
    val =[]
    for message in messages:
        val.append(message)
    return val[-20:]

#def setupCombat(request, cmbEnc):
#    combatEncounter = combatEncounter.objects.get(id = cmbEnc)
#    cmb = combat.objects.create()
#    newGroup = group.objects.create()
#    userGroup = profile.objects.get(request.session['profileID']).group
#    cmb.sideA = newGroup
#    cmb.sideB = userGroup
#    for x in combatEncounter.encounterCombatants.all():
#        for combatIndividual in xrange(0,x.quantity):
#            ind = combatIndividual.spawnIdividual()
#            ind.group = newGroup
#            cmb.addIndividualToCombat(ind, x.controler)
#    for ind in userGroup.allMonsters():
#        cmb.addIndividualToCombat(indl)
#    cmb.addMessage(combatEncounter.message)
#    cmb.save()
#    return showCombat(request, cmb.id)
             
    